package com.googlecode.easyibatis.spring.dao;
/**
 * 
 */

import java.sql.SQLException;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ApplicationObjectSupport;


import com.googlecode.easyibatis.core.exception.EasyIbatisException;
import com.ibatis.common.jdbc.exception.NestedSQLException;

/**
 * @author zxq
 * 
 */
public abstract class AbstractSupport extends ApplicationObjectSupport {
	protected final org.apache.commons.logging.Log logger = LogFactory.getLog(this.getClass());
	/**
	 * 
	 * @param e
	 * @return
	 */
	protected EasyIbatisException parseException(Throwable e) {
		if (logger.isErrorEnabled()) {
			logger.error(e.getMessage(), e);
		}
		if (e instanceof SQLException) {
			SQLException ex = (SQLException) ((e instanceof NestedSQLException) ? (e.getCause()) : e);
			int errorCode = ex.getErrorCode();
			String errorMessage = ex.getMessage();
			return refineException(errorCode, errorMessage);
		} else if (e instanceof EasyIbatisException) {
			return (EasyIbatisException) e;
		} else if (e instanceof Exception) {
			return new EasyIbatisException(e.getMessage(), (Exception) e);
		}
		return new EasyIbatisException(e.getMessage());
	}

	/**
	 * 
	 * @param errorCode
	 * @param errorMessage
	 * @return
	 */
	private EasyIbatisException refineException(int errorCode, String errorMessage) {
		if (errorCode == 1461) {
			return new EasyIbatisException("超过字段范围的值");
		}
		String[] array = StringUtils.split(errorMessage, "[':''\n']");
		if (ArrayUtils.isNotEmpty(array) && array.length >= 2) {
			return new EasyIbatisException(array[1]);
		} else {
			return new EasyIbatisException(errorMessage);
		}
	}
}
